package cn.edu.ctbu.interceptor;

import cn.edu.ctbu.exception.BaseException;
import cn.edu.ctbu.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    HttpServletResponse httpServletResponse;
    @Override//目标资源运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");

    }
    @Override//目标资源方法运行前运行，返回ture放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //获取请求头的的令牌token
        String jwt = request.getHeader("Authorization");
        log.info(jwt);

        //判断令牌是否存在，不存在返回错误就结果
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头中的token信息为空，返回未登录的信息");
            httpServletResponse.setStatus(401);
            throw new BaseException("该用户未登录账号！");
        }
        //解析token失败，返回错误结果
        try{
            JWTUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败，返回错误信息");
            response.setStatus(401);
            throw new BaseException("登录已失效！");
        }

//        放行
        log.info("令牌配对成功，放行！");
        return true;
    }



    @Override//视图渲染后完成，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion(完成后完成)...");
    }
}
